/* global util: false, Namespace: false */
"use strict";
var jNs = (function() {
    var nsTable = {};

    // 找出多级命名空间名称和 defining 函数
    function parseArgs() {
        var r = {};
        var isFound = false;

        r.names = [].filter.call(arguments, function(arg) {
            if (isFound) {
                return false;
            }

            if ({}.toString.call(arg) === "[object String]") {
                return arg;
            }

            if (util.isFunction(arg)) {
                r.defining = arg;
                isFound = true;
            }

            return false;
        });

        return r;
    }

    function jNs() {
        var args = parseArgs.apply(null, arguments);
        var name = util.mergeNs.apply(null, args.names);

        util.validateName(name);

        var ns = nsTable[name];
        if (!ns) {
            ns = nsTable[name] = new Namespace(name);
        }

        if (args.defining) {
            args.defining.call(ns, ns.define.bind(ns), ns.use.bind(ns));
        }

        return ns;
    }

    return jNs;
})();
